package com.oncliedisk.administrator.fragment;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Environment;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.ScaleAnimation;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.oncliedisk.administrator.DB.Dao;
import com.oncliedisk.administrator.adapter.FileAdapter;
import com.oncliedisk.administrator.content.FileConfig;
import com.oncliedisk.administrator.content.OnlineConfig;
import com.oncliedisk.administrator.interfaces.IDataCallback;
import com.oncliedisk.administrator.interfaces.OnDownLoadFinishListener;
import com.oncliedisk.administrator.interfaces.OnFileDownListener;
import com.oncliedisk.administrator.model.EntryModel;
import com.oncliedisk.administrator.model.Event;
import com.oncliedisk.administrator.model.FileTaskModel;
import com.oncliedisk.administrator.onlinedisk.R;
import com.oncliedisk.administrator.ui.ApplicationActivity;
import com.oncliedisk.administrator.ui.BtActivity;
import com.oncliedisk.administrator.ui.DocumentActivity;
import com.oncliedisk.administrator.ui.MusicActivity;
import com.oncliedisk.administrator.ui.OthersActivity;
import com.oncliedisk.administrator.ui.PhotoActivity;
import com.oncliedisk.administrator.ui.SearchActivity;
import com.oncliedisk.administrator.ui.UploadDocumentActiv;
import com.oncliedisk.administrator.ui.UploadMusicActivity;
import com.oncliedisk.administrator.ui.UploadOthersActivity;
import com.oncliedisk.administrator.ui.UploadPictureActivity;
import com.oncliedisk.administrator.ui.UploadVideoActivity;
import com.oncliedisk.administrator.ui.VideoActivity;
import com.oncliedisk.administrator.utils.DownloadFile;
import com.oncliedisk.administrator.utils.FileUtils;
import com.oncliedisk.administrator.utils.HttpUtils;
import com.oncliedisk.administrator.utils.MyFileComparator;
import com.oncliedisk.administrator.utils.OnlineUtils;
import com.vdisk.android.VDiskAuthSession;
import com.vdisk.net.VDiskAPI;
import com.vdisk.net.exception.VDiskException;
import com.ypy.eventbus.EventBus;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2015/12/3.
 * 文件目录页面
 */
public class FragMentFile extends android.support.v4.app.Fragment implements AdapterView.OnItemClickListener, View.OnClickListener, AdapterView.OnItemLongClickListener, SwipeRefreshLayout.OnRefreshListener, IDataCallback {
    private static final int REQUEST_RENAME = 1000;
    private ListView listview; //ListView
    private FileAdapter mAdapter; //适配器
    private String currPath = "/"; //当前ID
    private String currPosition = "0";
    private static Context context;
    private ImageView sort; //排序图片
    private ImageView newFile; //新建
    private ImageView search;//搜索
    private EditText newFileNmae; //新建文件名
    private Button newFileYes; //确定创建文件夹o
    private Button nintewFileNo; //取消创建文件夹
    private View dialog_view; //Dialog的视图
    AlertDialog.Builder builder;
    private AlertDialog alertDialog; //新建对话框
    private LinearLayout layout; //layout
    private PopupWindow window;
    private TextView order_name; //名字排序
    private TextView order_tiem; //时间排序
    private boolean isTime = false;
    private String paths = "网盘"; //路径
    private TextView tv_path; //路径文本
    private boolean isLongClick = false; //长按状态
    private Button cancel; //取消
    private Button allSelecd; //全选
    private Button newFileNo;
    private TextView selecedNumber; //当前选中几个
    private RelativeLayout longClickLayout; //长按layout
    private boolean isAllSeleced; //全选状态
    private LinearLayout showLongLayout; //全选状态工具栏
    private ImageView openFile_img; //打开文件图标
    private TextView openFile_txt; //打开文件文字
    private int[] img_grey = {R.drawable.open_grey, R.drawable.down_grey, R.drawable.delete_grey, R.drawable.more_grey};
    private int[] img_white = {R.drawable.open_white, R.drawable.down_white, R.drawable.delete_white, R.drawable.more_white};
    private int currSelseNum; //当前选中了几个
    private List<EntryModel> seleedModel; //当前选中的集合对象
    private LinearLayout upload; //上传布局
    private LinearLayout classify; //分类布局
    private GridView gview; //GridView
    private PopupWindow popupWindow; //弹出窗口
    // 图片封装为一个数组
    private int[] icon = {R.mipmap.netdisk_category_document_normal, R.mipmap.netdisk_category_audio_normal,
            R.mipmap.netdisk_category_image_normal, R.mipmap.netdisk_upload_category_video_normal, R.mipmap.netdisk_category_other_normal,
    };
    private String[] iconName = {"文档", "音乐", "图片", "视频", "其他",
    };
    private List<Map<String, Object>> data_list;
    private SimpleAdapter sim_adapter;
    private View gviewParent;
    private GridView gview1;
    private GridView gview2;
    private List<Map<String, Object>> data_list1;
    private SimpleAdapter sim_adapter1;
    private PopupWindow popupWindow1;
    private View gviewParent1;
    private Button button;
    // 图片封装为一个数组
    private int[] icon1 = {R.drawable.netdisk_category_image_normal, R.drawable.netdisk_category_document_normal,
            R.drawable.netdisk_category_audio_normal,
            R.drawable.netdisk_category_bt_normal,
            R.drawable.netdisk_upload_category_video_normal, R.drawable.netdisk_category_apk_normal, R.drawable.netdisk_category_other_normal};
    private String[] iconName1 = {"照片", "文档", "音乐", "BT种子", "视频", "应用", "其他",
    };
    private String postfix; //当前重命名的文件后缀
    private VDiskAPI<VDiskAuthSession> mApi;
    private int downNum; //需要下载的总个数
    private int downSuccessNum; //下载成功的个数
    private Button refer;
    private AlertDialog refer_dialog;
    private int downNumb; //总下载数
    private int currDownNum; //当前下载了多少
    private SwipeRefreshLayout swipeRefreshLayout;
    ProgressDialog progressDialog;
    private android.os.Handler handler = new android.os.Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            int what = msg.what;
            switch (what) {
                case OnlineConfig.CREATE_FOLDER:
                    //创建文件夹成功
                    Toast.makeText(getActivity(), "创建成功", Toast.LENGTH_SHORT).show();
                    VDiskAPI.Entry entr = (VDiskAPI.Entry) msg.obj;
                    //存储到数据库中，再进行查找
                    Dao db = Dao.getInstance(getActivity());
                    ArrayList<VDiskAPI.Entry> list = new ArrayList<VDiskAPI.Entry>();
                    list.add(entr);
                    db.saveFile(null, list, null);
                    String pat = currPath + "/";
                    mAdapter = new FileAdapter(Dao.getInstance(getActivity()).getAllFile("parent_url=?", new String[]{currPath.equals("/") ? currPath : pat}), getActivity(),listview);
                    listview.setAdapter(mAdapter);
                    mAdapter.notifyDataSetChanged();
                    alertDialog.dismiss();
                    break;
                case OnlineConfig.DOWN_IMAGE_FINISH:
                    Bundle bundle = msg.getData();
                    String url = bundle.getString("url");
                    EntryModel model = (EntryModel) bundle.getSerializable("model");
                    model.setDownPath(url);
                    Dao.getInstance(getActivity()).updateDownPath(url,"", model.getId());
                    mAdapter.notifyDataSetChanged();
                    Log.i("info", "设置图片下载地址" + url);
                    break;
            }

        }
    };

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.frag_file, null);
        initWeight(view);
        initData();
        initListener();
        return view;
    }

    /**
     * 初始化控件
     *
     * @param view
     */
    private void initWeight(View view) {
        listview = (ListView) view.findViewById(R.id.file_main_listview);
        sort = (ImageView) view.findViewById(R.id.file_sort);
        newFile = (ImageView) view.findViewById(R.id.file_newfile);
        search = (ImageView) view.findViewById(R.id.file_search);
        context = getActivity();
        layout = (LinearLayout) view.findViewById(R.id.file_layout);
        tv_path = (TextView) view.findViewById(R.id.file_path);
        cancel = (Button) view.findViewById(R.id.file_cancel);
        allSelecd = (Button) view.findViewById(R.id.file_allselecd);
        selecedNumber = (TextView) view.findViewById(R.id.file_selenumber);
        longClickLayout = (RelativeLayout) view.findViewById(R.id.file_layout_longclick);
        showLongLayout = (LinearLayout) view.findViewById(R.id.file_showLonglayout);
        upload = (LinearLayout) view.findViewById(R.id.file_layout_upload);
        classify = (LinearLayout) view.findViewById(R.id.file_layout_classify);
        LinearLayout open_layout = (LinearLayout) showLongLayout.getChildAt(0);
        openFile_img = (ImageView) open_layout.getChildAt(0);
        openFile_txt = (TextView) open_layout.getChildAt(1);
        seleedModel = new ArrayList<EntryModel>();
        refer = (Button) view.findViewById(R.id.file_refer);
        swipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.file_pulltorefer);
        //显示ProgressDialog
    }


    /**
     * 初始化监听
     */
    private void initListener() {
        listview.setOnItemClickListener(this);
        sort.setOnClickListener(this);
        newFile.setOnClickListener(this);
        search.setOnClickListener(this);
        listview.setOnItemLongClickListener(this);
        cancel.setOnClickListener(this);
        allSelecd.setOnClickListener(this);
        upload.setOnClickListener(this);
        classify.setOnClickListener(this);
        refer.setOnClickListener(this);
        //给长按工具界面的功能都设置监听
        for (int i = 0; i < showLongLayout.getChildCount(); i++) {
            showLongLayout.getChildAt(i).setOnClickListener(this);
        }
    }

    /**
     * 初始化数据
     */
    private void initData() {
        mAdapter = new FileAdapter(new ArrayList<EntryModel>(), getActivity(),listview);
        EventBus.getDefault().register(this);
        mApi = OnlineUtils.getMapi(getActivity());
        initDataBase(); //初始化数据
        initGridView(); //初始化menu
        initGridView1();
        initRefer(); // 初始化下拉刷新
    }

    /**
     * 初始化下拉刷新
     */
    private void initRefer() {
        swipeRefreshLayout.setOnRefreshListener(this);
        swipeRefreshLayout.setColorSchemeResources(android.R.color.holo_blue_bright,
                android.R.color.holo_green_light, android.R.color.holo_orange_light,
                android.R.color.holo_red_light);
    }


    /**
     * 初始化数据的数据，第一次启动应用的时候，在这里吧网盘上的所有文件获取下来，存储到数据库中，之后再对数据库进行操作
     */
    private void initDataBase() {
        boolean networkAvailable = HttpUtils.getInstance().isNetworkAvailable(getActivity());
        //一开始都获取数据库消息
        updateData();
        if (networkAvailable) {
            SharedPreferences isloadin = getActivity().getSharedPreferences("isloadin", context.MODE_PRIVATE);
            boolean isLoading = isloadin.getBoolean("isLoading", false);
            //如果没有查询过所有的数据，则进行查询
            //如果有网络，我就执行查询根目录的文件存入数据库，并且重新更新目录界面
            if (isLoading == false) {
                HttpUtils.getInstance().getALLFile(getActivity(), mApi, "/", new OnDownLoadFinishListener() {

                    @Override
                    public void onSuccess(List<VDiskAPI.Entry> data) {
                        Toast.makeText(getActivity(), "根目录成功", Toast.LENGTH_SHORT).show();
                        //当成功获取到网络的所有文件数据的时候调用
                        updateData();
                        if(data != null && data.size()>0){
//                            loadingData(data);
                        }
                        SharedPreferences isloadin = getActivity().getSharedPreferences("isloadin", context.MODE_PRIVATE);
                        SharedPreferences.Editor edit = isloadin.edit();
                        edit.putBoolean("isLoading", true);
                        edit.commit();
                        if(swipeRefreshLayout != null){
                            swipeRefreshLayout.setRefreshing(false);
                        }
                    }

                    @Override
                    public void onFail(String info) {
                        //获取失败
                        Toast.makeText(getActivity(), info, Toast.LENGTH_SHORT).show();
                    }
                });
            }
        }else{
            Toast.makeText(getActivity(), "请检查网络状态！", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 加载子目录数据存入数据库
     */
    public void loadingData(List<VDiskAPI.Entry> data) {
        Toast.makeText(getActivity(), "加载子目录", Toast.LENGTH_SHORT).show();
        for (VDiskAPI.Entry item : data) {
            if (item.isDir) {
                //子目录需要下载的个数
                //如果是文件夹，根据文件路径获取文件下的文件,进行存储到数据库中
                HttpUtils.getInstance().getALLFile(getActivity(), mApi, item.path + "/", new OnDownLoadFinishListener() {

                    @Override
                    public void onSuccess(List<VDiskAPI.Entry> data) {
                        //当成功获取到网络的所有文件数据的时候调用
                        loadingData(data);
                    }

                    @Override
                    public void onFail(String info) {
                        //获取失败
                        Toast.makeText(getActivity(), "子目录存储失败" + info, Toast.LENGTH_SHORT).show();
                    }
                });
            }
        }
    }

    /**
     * 更新本页面的数据
     */
    public void updateData() {
        Dao db = Dao.getInstance(getActivity());
        List<EntryModel> allFile = Dao.getInstance(getActivity()).getAllFile("parent_url=?", new String[]{currPath.equals("/") ? currPath : currPath + "/"});
        mAdapter.getData().clear();
        mAdapter.getData().addAll(allFile);
        mAdapter.notifyDataSetChanged();
        listview.setAdapter(mAdapter);
        for (final EntryModel model : mAdapter.getData()) {
            if (TextUtils.isEmpty(model.getDownPath())) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            VDiskAPI.VDiskLink media = mApi.media(model.getPath(), false);
                            Message message = handler.obtainMessage();
                            message.obj = media.url;
                            Bundle bundle = new Bundle();
                            bundle.putString("url", media.url);
                            bundle.putSerializable("model", model);
                            message.setData(bundle);
                            message.what = OnlineConfig.DOWN_IMAGE_FINISH;
                            handler.sendMessage(message);
                        } catch (VDiskException e) {
                            e.printStackTrace();
                        }
                    }
                }).start();
            }
        }
    }

    /**
     * 初始化GridView
     */
    private void initGridView() {
        gviewParent = View.inflate(getActivity(), R.layout.test, null);
        gview = (GridView) gviewParent.findViewById(R.id.gview);
        // 新建List
        data_list = new ArrayList<Map<String, Object>>();
        // 获取数据
        getData();
        // 新建适配器
        String[] from = {"image", "text"};
        int[] to = {R.id.image, R.id.text};
        sim_adapter = new SimpleAdapter(getActivity(), data_list, R.layout.item, from,
                to);
        // 配置适配器
        gview.setAdapter(sim_adapter);

        gview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                Intent intent;
                switch (position) {
                    case 1:
                        intent = new Intent(getActivity(), UploadMusicActivity.class);
                        intent.putExtra("desPath", currPath);
                        startActivity(intent);
                        break;
                    case 2:
                        intent = new Intent(getActivity(), UploadPictureActivity.class);
                        intent.putExtra("desPath", currPath);
                        startActivity(intent);
                        break;
                    case 3:
                        intent = new Intent(getActivity(), UploadVideoActivity.class);
                        intent.putExtra("desPath", currPath);
                        startActivity(intent);
                        break;
                    case 0:
                        intent = new Intent(getActivity(), UploadDocumentActiv.class);
                        intent.putExtra("desPath", currPath);
                        startActivity(intent);
                        break;
                    case 4:
                        intent = new Intent(getActivity(), UploadOthersActivity.class);
                        intent.putExtra("desPath", currPath);
                        startActivity(intent);
                        break;
                    default:
                        Toast.makeText(getActivity(), "并没有实现", Toast.LENGTH_SHORT).show();
                        break;
                }
            }
        });
    }

    /**
     * 初始化GridView
     */
    private void initGridView1() {
        gviewParent1 = View.inflate(getActivity().getApplicationContext(), R.layout.test, null);
        gview1 = (GridView) gviewParent1.findViewById(R.id.gview);
        // 新建List
        data_list1 = new ArrayList<Map<String, Object>>();
        // 获取数据
        getDataForClass();
        // 新建适配器
        String[] from = {"image", "text"};
        int[] to = {R.id.image, R.id.text};
        sim_adapter1 = new SimpleAdapter(getActivity(), data_list1, R.layout.item, from,
                to);
        // 配置适配器
        gview1.setAdapter(sim_adapter1);
        gview1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                switch (position) {
                    case 0:
                        Intent intent = new Intent(getActivity(), PhotoActivity.class);
                        startActivity(intent);
                        // startActivity(new  Intent(MainActivity.this,Photo.class));
                        break;
                    case 1:
                        startActivity(new Intent(getActivity(), DocumentActivity.class));
                        break;
                    case 2:
                        startActivity(new Intent(getActivity(), MusicActivity.class));
                        break;
                    case 3:
                        startActivity(new Intent(getActivity(), BtActivity.class));
                        break;
                    case 4:
                        startActivity(new Intent(getActivity(), VideoActivity.class));
                        break;
                    case 5:
                        startActivity(new Intent(getActivity(), ApplicationActivity.class));
                        break;
                    case 6:
                        startActivity(new Intent(getActivity(), OthersActivity.class));
                        break;
                    default:
                        Toast.makeText(getActivity(), "sorry", Toast.LENGTH_SHORT);

                }
                popupWindow1.dismiss();
            }
        });
    }

    /**
     * 获取上传数据
     *
     * @return
     */
    public List<Map<String, Object>> getData() {
        // cion和iconName的长度是相同的，这里任选其一都可以
        for (int i = 0; i < icon.length; i++) {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("image", icon[i]);
            map.put("text", iconName[i]);
            data_list.add(map);
        }
        return data_list;
    }


    /**
     * 把旧的弹出窗体关闭掉。
     */
    private void dismissPopupWindow() {
        if (popupWindow != null && popupWindow.isShowing()) {
            popupWindow.dismiss();
            popupWindow = null;
        }
    }

    /**
     * activity销毁时要把冒泡窗体关闭置空
     */
    @Override
    public void onDestroy() {
        dismissPopupWindow();
        super.onDestroy();
    }


    @Override
    public void onResume() {
        dismissPopupWindow();
        super.onResume();
    }

    /**
     * 当点击条目的时候触发
     *
     * @param parent
     * @param view
     * @param position
     * @param id
     */
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        EntryModel item = (EntryModel) mAdapter.getItem(position);
        if (isLongClick == true) {
            //如果现在是长按状态,则点击的这个设置成选中状态
            item.setIsCheck(!item.isCheck());
            updateAdapter();
            return;
        }
        //点击文件夹
        String type = item.getMimeType();
        if (type.equals(FileConfig.TYPE_FOLDER)) {
            //如果是文件夹,则打开文件夹
            mAdapter = new FileAdapter(Dao.getInstance(getActivity()).getAllFile("parent_url=?", new String[]{item.path + "/"}), getActivity(),listview);
            listview.setAdapter(mAdapter);
            currPath = item.path;
            currPosition = currPosition + "/" + position;
            paths += "/" + item.getFileName();
            tv_path.setText(currPath);
        } else {
            openFile(item);
        }
    }

    private long lastTime = 0;

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == event.KEYCODE_BACK) {

            if (isLongClick) {
                //如果在长按状态下按了返回，则退出长按状态
                cancelLongClick();
                return false;
            }
            if (currPath.equals("/")) {
                //如果已经是目录了，就不退了
                if (System.currentTimeMillis() - lastTime < 2000) {
                    //如果当前时间减去上次的时间，大于2秒
                    getActivity().finish();
                } else {
                    //如果不大于
                    Toast.makeText(getActivity(), "连续按两次退出", Toast.LENGTH_SHORT).show();
                    lastTime = System.currentTimeMillis();
                }
                return false;
            }
            //把当前路径分割，获取当前目录的上一个目录的ID
            if (currPath.contains("/")) {
                currPath = currPath.substring(0, currPath.lastIndexOf("/"));
            }
            String[] positons = currPosition.split("/");
            if (currPath.equals("")) {
                currPath = "/";
                mAdapter = new FileAdapter(Dao.getInstance(getActivity()).getAllFile("parent_url=?", new String[]{"/"}), getActivity(),listview);
            } else {
                mAdapter = new FileAdapter(Dao.getInstance(getActivity()).getAllFile("parent_url=?", new String[]{currPath + "/"}), getActivity(),listview);
            }
            listview.setAdapter(mAdapter);
            try {
                listview.setSelection(Integer.valueOf(positons[positons.length - 1]));
            } catch (Exception ex) {
                Log.i("info", "转换异常216行");
            }
            tv_path.setText(currPath.equals("/") ? "网盘" : currPath);
            return false;
        }
        return true;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {

            case R.id.file_sort:
                //排序
                openPopupWindown();
                break;
            case R.id.file_refer:
                //刷新
                break;
            case R.id.file_newfile:
                //新建
                newFile();
                break;

            case R.id.file_search:
                //搜索
                startActivity(new Intent(getActivity(), SearchActivity.class));
                break;

            case R.id.newfile_yes:
                //确定创建文件夹
                createFolder();
                break;

            case R.id.newfile_cancel:
                //取消
                alertDialog.dismiss();
                break;

            case R.id.order_name:
                //点击了按名字排序
                orderByName();
                break;

            case R.id.order_time:
                //点击了按时间排序
                orderByTime();
                break;

            case R.id.file_cancel:
                //取消
                cancelLongClick();
                break;

            case R.id.file_allselecd:
                //全选
                selecedAll();
                break;

            case R.id.file_more_open:
                //打开文件
                openFile(seleedModel.get(0));
                break;

            case R.id.file_more_delete:
                //删除文件
                deleteFile();
                break;

            case R.id.file_more_down:
                //下载文件
                if (!HttpUtils.isNetworkAvailable(getActivity())) {
                    Toast.makeText(getActivity(), "请检查网络状态是否可用!", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (seleedModel.size() > 0) {
                    //可以进行下载，存入数据库，并且加入下载队列
                    int index = 0;
                    for (EntryModel model : seleedModel) {
                        File file = new File(OnlineConfig.DOWN_DIRECTORY + model.getFileName());
                        File file_vd = new File(OnlineConfig.DOWN_DIRECTORY + model.getFileName() + ".vdisktemp");
                        if (file.exists()) {
                            Toast.makeText(getActivity(), "文件已下载，存储在下载目录中", Toast.LENGTH_SHORT).show();
                        } else if (file_vd.exists()) {
                            Toast.makeText(getActivity(), "文件已加入下载列表!", Toast.LENGTH_SHORT).show();
                        } else {
                            Log.i("info", "执行插入");
                            FileTaskModel taskModel = new FileTaskModel();
                            taskModel.setFileName(model.getFileName());
                            taskModel.setPath(model.getPath());
                            taskModel.setProgress("0");
                            taskModel.setShal(model.getSha1());
                            taskModel.setType(model.getMimeType());
                            taskModel.setSize(model.getSize());
                            taskModel.setState(FileTaskModel.STATE_WAIT_DOWN);
                            taskModel.setTaskType(OnlineConfig.TYPE_DOWN);
                            Dao.getInstance(getActivity()).saveFileTask(taskModel);
                        }
                    }
                    //存储完成，执行提醒传输页面.
                    EventBus.getDefault().post(new String(OnlineConfig.TYPE_DOWN));
                    cancelLongClick();
                }
                break;

            case R.id.file_more_more:
                //更多
                if (currSelseNum <= 0) {
                    //如果没有选中东西,则直接退出
                    break;
                }
                openMore();
                break;

            case R.id.more_move:
                //移动文件
                moveFile();
                break;

            case R.id.more_rename:
                //打开重命名
                if (seleedModel.size() == 1) {
                    openReName();
                    window.dismiss();
                }
                break;


            case R.id.dialog_yes:
                // Todo 重命名
                //确定更改名字
                reName();
                break;

            case R.id.dialog_cancel:
                //取消Dialog
                alertDialog.dismiss();
                break;
            case R.id.file_layout_upload:
                //打开上传
                //上传
                popupWindow = new PopupWindow(gviewParent, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                if (popupWindow.isShowing()) {
                    popupWindow.dismiss();
                }
                popupWindow.setOutsideTouchable(true);
                popupWindow.setFocusable(true);
                popupWindow.setBackgroundDrawable(new BitmapDrawable());
                // 动画效果的播放必须要求窗体有背景颜色。
                // 透明颜色也是颜色
                popupWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
                int[] location = new int[2];
                gview.getLocationInWindow(location);
                ImageView child = (ImageView) gview.findViewById(R.id.image);
                try {
                    popupWindow.showAsDropDown(v, -2, -2);
                } catch (Exception ex) {

                }
                ScaleAnimation sa = new ScaleAnimation(0.3f, 1.0f, 0.3f, 1.0f, Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0.5f);
                sa.setDuration(300);
                AlphaAnimation aa = new AlphaAnimation(0.5f, 1.0f);
                aa.setDuration(300);
                AnimationSet set = new AnimationSet(false);
                set.addAnimation(aa);
                set.addAnimation(sa);
//                gview.startAnimation(set);
                break;

            case R.id.file_layout_classify:
                //分类
                popupWindow1 = new PopupWindow(gviewParent1, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                popupWindow1.setOutsideTouchable(true);
                popupWindow1.setFocusable(true);
                if (popupWindow1.isShowing()) {
                    popupWindow1.dismiss();
                }
                // 动画效果的播放必须要求窗体有背景颜色。
                // 透明颜色也是颜色
                popupWindow1.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
                int[] location1 = new int[2];
                gview1.getLocationInWindow(location1);
                popupWindow1.showAsDropDown(v, -2, -2);

                ScaleAnimation sa1 = new ScaleAnimation(0.3f, 1.0f, 0.3f, 1.0f, Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0.5f);
                sa1.setDuration(300);
                AlphaAnimation aa1 = new AlphaAnimation(0.5f, 1.0f);
                aa1.setDuration(300);
                break;
        }
    }

    //下载文件
    private void downloadFile(EntryModel model, String path, OnFileDownListener onFileDownListener) {
        //TODO 下载文件
        String targetPath = Environment.getExternalStorageDirectory()
                .getAbsolutePath() + "/VDisk_SDK_cache/" + path;
        DownloadFile downloadFile = new DownloadFile(model, getActivity(), mApi, path, targetPath, onFileDownListener);
        downloadFile.execute();
    }

    /**
     * 打开分类
     */
    private void openClassify(View v) {
        popupWindow1 = new PopupWindow(gviewParent1, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        popupWindow1.setOutsideTouchable(true);
        popupWindow1.setFocusable(true);
//                popupWindow1.setBackgroundDrawable(new BitmapDrawable());
        if (popupWindow1.isShowing()) {
            popupWindow1.dismiss();
        }
        // 动画效果的播放必须要求窗体有背景颜色。
        // 透明颜色也是颜色
        popupWindow1.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        int[] location1 = new int[2];
        gview1.getLocationInWindow(location1);
//                ImageView child = (ImageView) gview.findViewById(R.id.image);
        popupWindow1.showAsDropDown(v, -2, -2);

        ScaleAnimation sa1 = new ScaleAnimation(0.3f, 1.0f, 0.3f, 1.0f, Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0.5f);
        sa1.setDuration(300);
        AlphaAnimation aa1 = new AlphaAnimation(0.5f, 1.0f);
        aa1.setDuration(300);
//                AnimationSet set = new AnimationSet(false);
//                set.addAnimation(aa);
//                set.addAnimation(sa);
//                gview.startAnimation(set);
    }

    /**
     * 打开上传
     */
    private void openUpLoad(View v) {
        popupWindow = new PopupWindow(gviewParent, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        if (popupWindow.isShowing()) {
            popupWindow.dismiss();
        }
        popupWindow.setOutsideTouchable(true);
        popupWindow.setFocusable(true);
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        // 动画效果的播放必须要求窗体有背景颜色。
        // 透明颜色也是颜色
        popupWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        int[] location = new int[2];
        gview.getLocationInWindow(location);
        ImageView child = (ImageView) gview.findViewById(R.id.image);
        try {
            popupWindow.showAsDropDown(v, -2, -2);
        } catch (Exception ex) {

        }
        ScaleAnimation sa = new ScaleAnimation(0.3f, 1.0f, 0.3f, 1.0f, Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0.5f);
        sa.setDuration(300);
        AlphaAnimation aa = new AlphaAnimation(0.5f, 1.0f);
        aa.setDuration(300);
        AnimationSet set = new AnimationSet(false);
        set.addAnimation(aa);
        set.addAnimation(sa);
//                gview.startAnimation(set);
    }

    /**
     * 移动文件
     */
    private void moveFile() {

    }

    /**
     * 重命名
     */
    private void reName() {
        final EntryModel entryModel = seleedModel.get(0);
        String newname = newFileNmae.getText().toString();
        Bundle session = new Bundle();
        int position = mAdapter.getData().indexOf(entryModel);
        Log.i("FragMentFile", "rename position" + position);
        session.putInt("position", position);
        session.putString("newname", newname);
        session.putString("parentPath", entryModel.getParent_url());
        HttpUtils.getInstance().rename(this, REQUEST_RENAME, entryModel.getParent_url(), entryModel.fileName, newname, mApi, session);
    }

    /**
     * 下载文件
     */
    private void downLoad() {
        Toast.makeText(getActivity(), "下载文件" + seleedModel.size() + "个", Toast.LENGTH_SHORT).show();
    }

    /**
     * 删除文件
     */
    private void deleteFile() {
        final AlertDialog deleteDialog = getDialog("删除操作", "正在删除，请稍等!");
        if (currSelseNum >= 1) {
            deleteDialog.show();
            HttpUtils.getInstance().deleteFile(getActivity(), mApi, seleedModel, new OnDownLoadFinishListener() {
                @Override
                public void onSuccess(List<VDiskAPI.Entry> data) {
                    //如果没有选中东西,则直接退出
                    Dao.getInstance(getActivity()).deleteModel(seleedModel);
                    mAdapter.getData().removeAll(seleedModel);
                    updateAdapter();
                    cancelLongClick();
                    deleteDialog.dismiss();
                }

                @Override
                public void onFail(String errorInfo) {
                    Toast.makeText(getActivity(), "错误消息" + errorInfo, Toast.LENGTH_SHORT).show();
                    Dao.getInstance(getActivity()).deleteModel(seleedModel);
                    mAdapter.getData().removeAll(seleedModel);
                    updateAdapter();
                    cancelLongClick();
                    deleteDialog.dismiss();
                }
            });

        }
    }

    /**
     * 根据指定信息，获取Dialog
     * @param title
     * @param message
     * @return
     */
    public AlertDialog getDialog(String title, String message) {
        AlertDialog.Builder dialog = new AlertDialog.Builder(getActivity());
        AlertDialog alertDialog = dialog.create();
        alertDialog.setTitle(title);
        alertDialog.setMessage(message);
        alertDialog.setCancelable(false);
        return alertDialog;
    }

    /**
     * 全选
     */
    private void selecedAll() {
        for (EntryModel model : mAdapter.getData()) {
            initModel(model);
            if (isAllSeleced) {
                model.setIsCheck(false);
                model.setIsLoading(true);
            } else {
                model.setIsLoading(false);
                model.setIsCheck(true);
            }
        }
        isAllSeleced = !isAllSeleced;
        updateAdapter();
    }

    /**
     * 根据时间排序
     */
    private void orderByTime() {
        Collections.sort(mAdapter.getData(), new MyFileComparator());
        mAdapter.notifyDataSetChanged();
        window.dismiss();
        order_tiem.setTextColor(getActivity().getResources().getColor(R.color.blue));
        order_name.setTextColor(getActivity().getResources().getColor(R.color.white));
        isTime = true;
    }

    /**
     * 根据名字排序
     */
    private void orderByName() {
        updateData();
        window.dismiss();
        order_name.setTextColor(getActivity().getResources().getColor(R.color.blue));
        order_tiem.setTextColor(getActivity().getResources().getColor(R.color.white));
        isTime = false;
    }

    /**
     * 创建文件夹
     */
    private void createFolder() {
        final String fileName = newFileNmae.getText().toString().trim();
        if (TextUtils.isEmpty(fileName)) {
            //如果为空
            Toast.makeText(getActivity(), "文件夹名字不可为空", Toast.LENGTH_SHORT).show();
        } else {
            new Thread() {
                @Override
                public void run() {
                    Message msg = new Message();
                    String error = "";
                    try {
                        VDiskAPI.Entry metaData = mApi.createFolder(currPath + "/" + fileName);
                        msg.what = OnlineConfig.CREATE_FOLDER;
                        msg.obj = metaData;
                    } catch (VDiskException e) {
                        e.printStackTrace();
                    }
                    handler.sendMessage(msg);
                }
            }.start();
        }
    }


    /**
     * 打开重命名窗口
     */
    private void openReName() {
        postfix = "";
        //初始化新建文件夹Dialog的控件
        View dialog_view = getActivity().getLayoutInflater().inflate(R.layout.item_dialog_rename, null);
        Button newFileNo = (Button) dialog_view.findViewById(R.id.dialog_cancel);
        newFileNmae = (EditText) dialog_view.findViewById(R.id.dialog_name);
        Button newFileYes = (Button) dialog_view.findViewById(R.id.dialog_yes);
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        EntryModel EntryModel = seleedModel.get(0);
        String s = EntryModel.getFileName().toString();
        if (s.contains(".")) {
            newFileNmae.setText(s.substring(0, s.lastIndexOf(".")));
            postfix = s.substring(s.lastIndexOf("."));
        } else {
            newFileNmae.setText(s);
        }
        newFileNmae.selectAll();
        alertDialog = builder.create();
        alertDialog.setView(dialog_view);
        alertDialog.show();
        newFileYes.setOnClickListener(this);
        newFileNo.setOnClickListener(this);
    }

    /**
     * 打开更多
     */
    private void openMore() {
        window = new PopupWindow(getActivity().getResources().getDisplayMetrics().widthPixels / 3, ViewGroup.LayoutParams.WRAP_CONTENT);
        View view = getActivity().getLayoutInflater().inflate(R.layout.item_pop_more, null);
        view.findViewById(R.id.more_move).setOnClickListener(this);
        view.findViewById(R.id.more_rename).setOnClickListener(this);
        ImageView more_img = (ImageView) view.findViewById(R.id.more_img);
        TextView more_tv = (TextView) view.findViewById(R.id.more_tv_rename);
        window.setContentView(view);
        window.setOutsideTouchable(true);
        window.setFocusable(true);
        window.setBackgroundDrawable(new BitmapDrawable());
        int[] widthAndHeightforView = FileUtils.getWidthAndHeightforView(showLongLayout);
        window.showAtLocation(showLongLayout, Gravity.RIGHT | Gravity.BOTTOM, 0, widthAndHeightforView[1]);
        if (seleedModel.size() == 1) {
            //说明只有选中一个，可以重命名操作
            more_img.setImageResource(R.mipmap.edit_tools_rename);
            more_tv.setTextColor(getResources().getColor(R.color.white));
        } else {
            more_img.setImageResource(R.mipmap.edit_tools_rename_disable);
            more_tv.setTextColor(getResources().getColor(R.color.disable));
        }
    }

    /**
     * 打开文件
     */
    private void openFile(EntryModel entryModel) {
        if (isLongClick && currSelseNum == 1 || isLongClick == false) {
            //你要打开文件，你如果是长按状态和你选中的只有一个,这样可以打开文件
            //如果选中的等于1,则可以进行打开
            if (entryModel != null) {
                if (entryModel.getMimeType().equals(FileConfig.TYPE_FOLDER)) {
                    //如果是文件夹，就打开文件夹
                    mAdapter = new FileAdapter(Dao.getInstance(getActivity()).getAllFile("parent_url=?", new String[]{entryModel.path + "/"}), getActivity(),listview);
                    listview.setAdapter(mAdapter);
                    currPath = entryModel.path;
                    paths += "/" + entryModel.getFileName();
                    tv_path.setText(currPath);
                    updateAdapter();
                    cancelLongClick();
                } else {
                    if (TextUtils.isEmpty(entryModel.getLocalpath())) {
                        //如果本地路径是空的，就是还没有下载，所以进行下载，下载完成后，进行打开
                        downloadFile(entryModel, entryModel.getPath(), new OnFileDownListener() {
                            @Override
                            public void onSuccess(EntryModel model) {
                                openFileByType(model.getLocalpath());
                            }

                            @Override
                            public void onFail(String errorInfo) {
                                Toast.makeText(getActivity(), "错误" + errorInfo, Toast.LENGTH_SHORT).show();
                            }
                        });
                    } else {
                        //如果有路径，则进行打开
                        openFileByType(entryModel.getLocalpath());
                    }
                    cancelLongClick();
                }
            }
        }

    }


    /**
     * 获取路径文件的后缀进行打开文件
     *
     * @param path
     */
    private void openFileByType(String path) {
        getActivity().startActivity(FileUtils.getInstance().openFile(path));
    }

    /**
     * 初始化状态
     *
     * @param model
     */
    private void initModel(EntryModel model) {
        model.setIsLoading(false);
        model.setIsCheck(false);
        model.setIsSingle(false);
    }


    /**
     * 打开排序选项，PopupWindow
     */
    private void openPopupWindown() {
        window = new PopupWindow(getActivity().getResources().getDisplayMetrics().widthPixels / 3, ViewGroup.LayoutParams.WRAP_CONTENT);
        View view = getActivity().getLayoutInflater().inflate(R.layout.item_popuorder, null);
        order_name = (TextView) view.findViewById(R.id.order_name);
        order_tiem = (TextView) view.findViewById(R.id.order_time);
        order_name.setOnClickListener(this);
        order_tiem.setOnClickListener(this);
        window.setContentView(view);
        window.setOutsideTouchable(true);
        window.setFocusable(true);
        window.setBackgroundDrawable(new BitmapDrawable());
        window.showAsDropDown(layout);
        if (isTime) {
            order_tiem.setTextColor(getActivity().getResources().getColor(R.color.blue));
            order_name.setTextColor(getActivity().getResources().getColor(R.color.white));
        } else {
            order_name.setTextColor(getActivity().getResources().getColor(R.color.blue));
            order_tiem.setTextColor(getActivity().getResources().getColor(R.color.white));
        }
    }

    /**
     * 新建文件夹
     */
    private void newFile() {
        //初始化新建文件夹Dialog的控件
        dialog_view = getActivity().getLayoutInflater().inflate(R.layout.item_dialog, null);
        newFileNo = (Button) dialog_view.findViewById(R.id.newfile_cancel);
        newFileNmae = (EditText) dialog_view.findViewById(R.id.newfile_name);
        newFileYes = (Button) dialog_view.findViewById(R.id.newfile_yes);
        builder = new AlertDialog.Builder(getActivity());
        alertDialog = builder.create();
        alertDialog.setView(dialog_view);
        alertDialog.show();
        newFileYes.setOnClickListener(this);
        newFileNo.setOnClickListener(this);
    }

    @Override
    public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
        if (isLongClick == false) {
            //如果现在不是长按状态,则进行长按操作
            List<EntryModel> data = mAdapter.getData();
            //把所有条目的对象都设置成等待选中状态
            for (EntryModel model : data) {
                model.setIsCheck(false);
                model.setIsLoading(false);
                model.setIsSingle(false);
                model.setIsLoading(true);
            }
            //把当前长按的这个条目设置为选中状态
            data.get(position).setIsCheck(true);
            updateAdapter();
            isLongClick = true;
            //设置长按界面开启
            longClickLayout.setVisibility(View.VISIBLE);
            showLongLayout.setVisibility(View.VISIBLE);
            //标题隐藏
            layout.setVisibility(View.INVISIBLE);
            return true;
        }
        return false;
    }

    /**
     * 退出长按事件
     */
    public void cancelLongClick() {
        List<EntryModel> data = mAdapter.getData();
        for (EntryModel model : data) {
            model.setIsSingle(true);
        }
        updateAdapter();
        isLongClick = false;
        layout.setVisibility(View.VISIBLE);
        longClickLayout.setVisibility(View.INVISIBLE);
        showLongLayout.setVisibility(View.GONE);
    }

    /**
     * 更新适配器
     */
    public void updateAdapter() {
        seleedModel.clear();
        mAdapter.notifyDataSetChanged();
        int selecedIndex = 0;
        for (EntryModel model : mAdapter.getData()) {
            if (model.isCheck()) {
                selecedIndex++;
                seleedModel.add(model);
            }
        }
        selecedNumber.setText("已选中" + selecedIndex + "个");
        currSelseNum = selecedIndex;
        for (int i = 0; i < showLongLayout.getChildCount(); i++) {
            LinearLayout childAt = (LinearLayout) showLongLayout.getChildAt(i);
            ImageView img = (ImageView) childAt.getChildAt(0);
            TextView txt = (TextView) childAt.getChildAt(1);
            img.setImageResource(selecedIndex >= 1 ? img_white[i] : img_grey[i]);
            txt.setTextColor(selecedIndex >= 1 ? getResources().getColor(R.color.white) : getResources().getColor(R.color.grey));
        }
        if (selecedIndex > 1) {
            openFile_img.setImageDrawable(getResources().getDrawable(R.drawable.open_grey));
            openFile_txt.setTextColor(getResources().getColor(R.color.grey));
        }
    }


    public List<Map<String, Object>> getDataForClass() {
        // cion和iconName的长度是相同的，这里任选其一都可以
        for (int i = 0; i < icon1.length; i++) {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("image", icon1[i]);
            map.put("text", iconName1[i]);
            data_list1.add(map);
        }
        return data_list1;
    }

    /**
     * 把旧的弹出窗体关闭掉。
     */
    private void dismissPopupWindowForClass() {
        if (popupWindow != null && popupWindow.isShowing()) {
            popupWindow.dismiss();
            popupWindow = null;
        }

        if (popupWindow1 != null && popupWindow1.isShowing()) {
            popupWindow1.dismiss();
            popupWindow1 = null;
        }
    }

    public void onEventMainThread(String type) {
        if (type.equals(OnlineConfig.TYPE_UP_SUCCESS)) {
            //如果上传完成，进行更新现在界面上的数据
            Toast.makeText(getActivity(), "上传完成，更新适配", Toast.LENGTH_SHORT).show();
            mAdapter = new FileAdapter(Dao.getInstance(getActivity()).getAllFile("parent_url=?", new String[]{currPath.equals("/") ? currPath : currPath + "/"}), getActivity(),listview);
            listview.setAdapter(mAdapter);
        }
    }

    /**
     * 如果刷新完成
     */
    @Override
    public void onRefresh() {
        //当要刷新的时候调用
        SharedPreferences isloadin = getActivity().getSharedPreferences("isloadin", context.MODE_PRIVATE);
        SharedPreferences.Editor edit = isloadin.edit();
        edit.putBoolean("isLoading", false);
        edit.commit();
        initDataBase();
        List<EntryModel> allFile = Dao.getInstance(getActivity()).getAllFile("parent_url=?", new String[]{currPath.equals("/") ? currPath : currPath + "/"});
        mAdapter.getData().clear();
        mAdapter.getData().addAll(allFile);
        mAdapter.notifyDataSetChanged();
        swipeRefreshLayout.setRefreshing(false);
    }

    @Override
    public void handleServiceResult(Event event, Bundle session) {
        switch (event.requestCode) {
            case REQUEST_RENAME:
                if (event.e == null) {
                    String parentPath = session.getString("parentPath");
                    Log.i("FragMentFile", "parentPath: " + parentPath);
                    int postion = session.getInt("position");
                    VDiskAPI.Entry entry = (VDiskAPI.Entry) event.data;
                    EntryModel entryModel = mAdapter.getData().get(postion);
                    entryModel.setFileName(entry.fileName());
                    if(entry.contents != null) {
                        entryModel.contents = entry.contents;
                        Log.i("handleServiceResult", "entryModel:contents::: " + entry.contents);
                    }
                    entryModel.bytes = entry.bytes;
                    entryModel.clientMtime = entry.clientMtime;
                    entryModel.downPath = entry.path;
                    entryModel.isDir = entry.isDir;
                    Toast.makeText(getActivity(), "重命名完成", Toast.LENGTH_SHORT).show();
                    mAdapter.notifyDataSetChanged();

                    Dao.getInstance(getActivity()).updateName(entryModel,entryModel.getFileName());
                    alertDialog.dismiss();
                } else {
                    Toast.makeText(getActivity(), "重命名失败", Toast.LENGTH_SHORT).show();
                    event.e.printStackTrace();
                }
                break;
        }
    }
}
